<template>
  <view class="rune-upgrade-container">
    <view class="section-header">
      <text class="section-title">符文升级</text>
      <text class="section-subtitle">将低级符文合成为高级符文</text>
    </view>
    
    <view class="loading" v-if="isLoading">
      <view class="loading-icon"></view>
      <text class="loading-text">加载符文数据中...</text>
    </view>
    
    <view class="error-message" v-if="loadError">
      <view class="error-icon">!</view>
      <text class="error-text">{{ loadError }}</text>
      <button class="retry-button" @click="onLoad">重试</button>
    </view>
    
    <view class="upgrade-interface" v-if="!isLoading && !loadError">
      <view class="input-section">
        <text class="input-label">选择要升级的符文:</text>
        <picker @change="onRuneSelect" :range="upgradeableRunes" range-key="from">
          <view class="picker">
            {{ selectedUpgrade ? selectedUpgrade.from : '请选择符文' }}
          </view>
        </picker>
      </view>
      
      <view class="requirements" v-if="selectedUpgrade">
        <text class="requirements-title">升级需求:</text>
        <view class="requirement-row">
          <image :src="getRuneImage(selectedUpgrade.from)" class="small-rune-icon" />
          <text>{{ selectedUpgrade.required }} × {{ selectedUpgrade.from }}</text>
        </view>
        <text class="requirement" v-if="selectedUpgrade.cost.gold">{{ selectedUpgrade.cost.gold }} 金币</text>
        
        <view class="batch-controls" v-if="playerRunes[selectedUpgrade.from] > selectedUpgrade.required">
          <text>批量升级:</text>
          <input 
            type="number" 
            v-model="batchCount"
            :max="maxBatchCount"
            min="1"
            class="batch-input"
          />
          <text>次 (最多{{ maxBatchCount }}次)</text>
        </view>
      </view>
      
      <view class="result" v-if="selectedUpgrade">
        <text class="result-title">升级结果:</text>
        <view class="result-rune">
          <image :src="getRuneImagePath(selectedUpgrade.to)" class="rune-image" />
          <text class="rune-name">{{ selectedUpgrade.to }}</text>
          <text class="rune-value" v-if="runeValues[selectedUpgrade.to]">
            价值: {{ runeValues[selectedUpgrade.to] }}金币
          </text>
        </view>
        <view class="value-comparison" v-if="runeValues[selectedUpgrade.from] && runeValues[selectedUpgrade.to]">
          <text>升级价值: {{ (runeValues[selectedUpgrade.to] - runeValues[selectedUpgrade.from] * selectedUpgrade.required) }}金币</text>
        </view>
      </view>
      
      <button 
        class="upgrade-button" 
        :disabled="!canUpgrade"
        @click="performUpgrade"
      >
        升级符文
      </button>
    </view>
  </view>
</template>

<script>
import { loadData } from '@/common/d2r-data/index.js'

export default {
  data() {
    return {
      upgrades: [],
      selectedUpgrade: null,
      playerRunes: {},
      playerGold: 0,
      batchCount: 1,
      runeValues: {}, // 符文价值数据
      isLoading: true,
      loadError: null
    }
  },
  
  computed: {
    upgradeableRunes() {
      return this.upgrades.filter(upgrade => 
        this.playerRunes[upgrade.from] >= upgrade.required
      )
    },
    
    canUpgrade() {
      if (!this.selectedUpgrade) return false
      const required = this.selectedUpgrade.required * this.batchCount
      const cost = (this.selectedUpgrade.cost.gold || 0) * this.batchCount
      return (
        this.playerRunes[this.selectedUpgrade.from] >= required &&
        this.playerGold >= cost
      )
    },
    
    maxBatchCount() {
      if (!this.selectedUpgrade) return 0
      const maxByRunes = Math.floor(this.playerRunes[this.selectedUpgrade.from] / this.selectedUpgrade.required)
      const maxByGold = this.selectedUpgrade.cost.gold 
        ? Math.floor(this.playerGold / this.selectedUpgrade.cost.gold)
        : Infinity
      return Math.min(maxByRunes, maxByGold)
    }
  },
  
  async onLoad() {
    this.isLoading = true
    try {
      // 直接导入本地数据
      import('@/common/d2r-data/rune-upgrades.json').then(module => {
        this.upgrades = module.default
      })
      import('@/common/d2r-data/rune-values.json').then(module => {
        this.runeValues = module.default
      })
      
      // 从本地存储加载玩家数据
      const savedData = uni.getStorageSync('playerRunes') || {}
      this.playerRunes = savedData.runes || {}
      this.playerGold = savedData.gold || 0
      
      // 如果没有数据，初始化基础符文
      if (Object.keys(this.playerRunes).length === 0) {
        this.playerRunes = { El: 3, Eld: 1 }
        this.savePlayerData()
      }
    } catch (e) {
      console.error('加载数据失败:', e)
      this.loadError = '加载数据失败，请检查网络连接'
      uni.showToast({
        title: '加载数据失败',
        icon: 'none'
      })
    } finally {
      this.isLoading = false
    }
  },
  
  methods: {
    savePlayerData() {
      uni.setStorageSync('playerRunes', {
        runes: this.playerRunes,
        gold: this.playerGold
      })
    },
    
    onRuneSelect(e) {
      this.selectedUpgrade = this.upgradeableRunes[e.detail.value]
    },
    
    getRuneImagePath(runeName) {
      return `/static/images/runes/${runeName.toLowerCase()}.svg`
    },
    
    performUpgrade() {
      if (!this.canUpgrade) return
      
      const count = this.batchCount
      const required = this.selectedUpgrade.required * count
      const cost = (this.selectedUpgrade.cost.gold || 0) * count
      
      // 扣除消耗
      this.playerRunes[this.selectedUpgrade.from] -= required
      this.playerGold -= cost
      
      // 添加新符文
      if (!this.playerRunes[this.selectedUpgrade.to]) {
        this.playerRunes[this.selectedUpgrade.to] = 0
      }
      this.playerRunes[this.selectedUpgrade.to] += count
      
      // 保存数据
      this.savePlayerData()
      
      // 播放音效
      uni.playBackgroundAudio({
        src: '/static/audio/upgrade-success.mp3'
      })
      
      uni.showToast({
        title: `成功升级获得 ${count}个 ${this.selectedUpgrade.to}`,
        icon: 'success'
      })
      
      // 重置选择
      this.selectedUpgrade = null
      this.batchCount = 1
    },
    
    // 添加获取符文图片方法
    getRuneImage(runeName) {
      return `/static/images/runes/${runeName.toLowerCase()}.png`
    }
  }
}
</script>

<style lang="scss">
@import '@/common/d2r-theme.scss';

// 临时加载样式
.loading-icon {
  width: 36px;
  height: 36px;
  border: 3px solid rgba($d2r-gold, 0.3);
  border-top-color: $d2r-gold;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.error-icon {
  width: 36px;
  height: 36px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.rune-upgrade-container {
  padding: 20px;
  background-color: $d2r-bg-dark;
  min-height: 100vh;
}

.loading, .error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  
  .loading-text, .error-text {
    margin-top: 15px;
    color: $d2r-text-secondary;
  }
}

.error-message {
  .error-text {
    color: #ff4d4f;
    margin: 15px 0;
  }
  
  .retry-button {
    background-color: $d2r-gold;
    color: $d2r-bg-dark;
    padding: 8px 16px;
    border-radius: 4px;
    margin-top: 10px;
  }
}

.upgrade-interface {
  background-color: $d2r-bg-medium;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  
  .small-rune-icon {
    width: 20px;
    height: 20px;
    margin-right: 8px;
  }
  
  .requirement-row {
    display: flex;
    align-items: center;
    margin: 5px 0;
  }
  
  .batch-controls {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid $d2r-border;
    display: flex;
    align-items: center;
    
    .batch-input {
      width: 60px;
      margin: 0 8px;
      padding: 4px;
      background-color: $d2r-bg-light;
      color: $d2r-text;
      text-align: center;
      border: 1px solid $d2r-border;
      border-radius: 4px;
    }
  }
}

.input-section {
  margin-bottom: 20px;
  
  .input-label {
    display: block;
    margin-bottom: 8px;
    color: $d2r-text-secondary;
  }
  
  .picker {
    background-color: $d2r-bg-light;
    padding: 12px;
    border-radius: 4px;
    color: $d2r-text;
  }
}

.requirements, .result {
  margin: 20px 0;
  padding: 15px;
  background-color: $d2r-bg-light;
  border-radius: 4px;
  
  .requirements-title, .result-title {
    display: block;
    font-weight: bold;
    margin-bottom: 10px;
    color: $d2r-gold;
  }
  
  .requirement {
    display: block;
    margin: 5px 0;
  }
}

.result-rune {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10px;
  padding: 15px;
  background-color: $d2r-bg-light;
  border-radius: 8px;
  
  .rune-image {
    width: 60px;
    height: 60px;
    margin-bottom: 10px;
  }
  
  .rune-name {
    font-size: 18px;
    color: $d2r-gold;
    margin-bottom: 5px;
  }
  
  .rune-value {
    font-size: 14px;
    color: $d2r-text-secondary;
  }
}

.value-comparison {
  margin-top: 10px;
  padding: 10px;
  background-color: rgba($d2r-gold, 0.1);
  border-radius: 4px;
  text-align: center;
  font-size: 14px;
  
  text {
    color: $d2r-gold;
  }
}

.upgrade-button {
  background-color: $d2r-gold;
  color: $d2r-bg-dark;
  font-weight: bold;
  padding: 12px;
  border-radius: 4px;
  text-align: center;
  margin-top: 20px;
  
  &[disabled] {
    opacity: 0.5;
  }
}
</style>